﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

namespace JWUX.Framework.Controls
{
    [ToolboxBitmap(typeof(DataGridView))]
    public class DataGridViewEx : DataGridView
    {
        #region 成员

        private bool _rowNumVisible = true;
        private Color _rowNumColor = Color.Black;
        private bool _allowSelectRow = true;

        #endregion

        #region 属性

        /// <summary>
        /// 获取或设置是否显示行号
        /// </summary>
        [Description("是否显示行号？")]
        [DefaultValue(true)]
        public bool RowNumVisible
        {
            get { return _rowNumVisible; }
            set
            {
                _rowNumVisible = value;
                base.Invalidate(); //刷新IDE显示效果
            }
        }

        /// <summary>
        /// 获取或设置行号颜色
        /// </summary>
        [Description("行号颜色，默认Color.Black")]
        [DefaultValue(typeof(Color), "Black")]
        public Color RowNumColor
        {
            get { return _rowNumColor; }
            set
            {
                _rowNumColor = value;
                base.Invalidate();
            }
        }

        /// <summary>
        /// 获取或设置是否允许选中行
        /// </summary>
        [Description("设置是否允许选中行")]
        [DefaultValue(typeof(Boolean), "True")]
        public bool AllowSelectRow
        {
            get { return _allowSelectRow; }
            set { _allowSelectRow = value; }
        }

        #endregion

        #region 构造和方法

        public DataGridViewEx()
            : base()
        {
        }

        #endregion

        #region 方法重写

        protected override void OnSelectionChanged(EventArgs e)
        {
            #region 是否允许选中行
            if (!_allowSelectRow && SelectedRows.Count > 0)
            {
                base.SelectedRows[0].Selected = false;
            }
            #endregion

            base.OnSelectionChanged(e);
        }

        protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
        {
            #region 是否显示行号

            if (_rowNumVisible)
            {
                Rectangle rectangle = new Rectangle(
                     e.RowBounds.Location.X,
                     e.RowBounds.Location.Y,
                     this.RowHeadersWidth - 4,
                     e.RowBounds.Height
                 );

                TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                    base.RowHeadersDefaultCellStyle.Font,
                    rectangle,
                    _rowNumColor,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Right
                );
            }

            #endregion

            base.OnRowPostPaint(e);
        }

        #endregion
    }
}
